package cn.ztydata.teachingsystem.heaven.service;

import cn.ztydata.teachingsystem.exception.ServiceException;
import cn.ztydata.teachingsystem.heaven.dao.ChapterOverviewDao;
import cn.ztydata.teachingsystem.heaven.entity.ChapterProfile;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 章节概况服务类
 * Created by chenxin on 2014/12/16.
 */
@Service
public class ChapterOverviewService extends BaseService {
    @Autowired
    private ChapterOverviewDao chapterOverviewDao;

    @Autowired
    private ChapterService chapterService;

    /**
     * 编辑保存章节概况内容
     * @param nodeId 节点ID
     * @param type 概况类型
     * @param content 概况内容
     *
     * @author cx
     * @since 2014-12-16
     */
    public void updateContent(final long nodeId, final int type, String content) {
        //判断节点是否可操作
        chapterService.checkNode(nodeId);

        if (!chapterOverviewDao.updateContent(nodeId, type, content)) {
            log.debug("更新章节概况内容失败:!chapterOverviewDao.updateContent(nodeId, type, content)");
            log.warn("更新章节概况内容失败:nodeId->" + nodeId);
            throw new ServiceException();
        }
    }

    /**
     * 获取指定的章节概况内容
     * @param nodeId 节点ID
     * @param type 概况类型
     * @return String
     *
     * @author cx
     * @since 2014-12-16
     */
    public ChapterProfile getContent(final long nodeId, final int type) {
        ChapterProfile content = chapterOverviewDao.getContent(nodeId, type);

        if(content.getContent() != null){
            content.setContent(StringEscapeUtils.unescapeHtml4(content.getContent()));
        }

        log.debug("获取指定的章节概况内容");
        return content;
    }

    /**
     * 获取概况是否为空
     * @param nodeId 节点ID
     * @return List
     *
     * @author cx
     * @since 2014-12-17
     */
    public List<Long> getForNull(final long nodeId) {
        Map<String, Object> nullTag = chapterOverviewDao.getForNull(nodeId);

        List<Long> result = Lists.newArrayList();
        if (nullTag == null) {
            log.debug("获取概况为空:nullTag == null");
            return result;
        }

        log.debug("获取概况是否为空: for (int i = 1; i <= 8; i++)");
        for (int i = 1; i <= 8; i++) {
            result.add((Long) nullTag.get(String.valueOf(i)));
        }

        log.debug("获取概况是否为空");
        return result;
    }
}
